package com.mxpio.erp.quality.service.impl;

import com.mxpio.erp.common.quality.entity.InspectionBillCheckDetail;
import com.mxpio.erp.common.quality.entity.InspectionBillDetect;
import com.mxpio.erp.common.quality.entity.InspectionItem;
import com.mxpio.erp.common.quality.service.InspectionBillDetectService;
import com.mxpioframework.jpa.JpaUtil;
import com.mxpioframework.jpa.query.Criteria;
import com.mxpioframework.system.service.impl.BaseServiceImpl;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;


@Service
public class InspectionBillDetectServiceImpl extends BaseServiceImpl<InspectionBillDetect> implements InspectionBillDetectService {
    @Override
    @Transactional
    public int deleteByBizNo(String bizNo) {
        return JpaUtil.lind(InspectionBillDetect.class).equal("bizNo", bizNo).delete();
    }

    @Override
    @Transactional
    public List<InspectionBillDetect> listWith(Criteria c) {
        return JpaUtil.linq(InspectionBillDetect.class)
                .collect("code", InspectionItem.class, "inspectionItemCode")
                .where(c)
                .list();
    }

    @Override
    @Transactional
    public void computeCheckedSimples(String bizNo, List<InspectionBillDetect> inspectionBillDetects) {
        if (CollectionUtils.isNotEmpty(inspectionBillDetects)){
            for (InspectionBillDetect simple:inspectionBillDetects){
                Long checkedCount = JpaUtil.linq(InspectionBillCheckDetail.class).equal("bizNo", bizNo).equal("detectCode", simple.getDetectCode()).isNotNull("testResult").count();
                simple.setCheckSimpleNum(checkedCount.intValue());
                Long qualifiedCount = JpaUtil.linq(InspectionBillCheckDetail.class).equal("bizNo", bizNo).equal("detectCode", simple.getDetectCode()).equal("testResult","1").count();
                simple.setQualifiedQuantity(new BigDecimal(qualifiedCount+""));
                Long unqualifiedCount = JpaUtil.linq(InspectionBillCheckDetail.class).equal("bizNo", bizNo).equal("detectCode", simple.getDetectCode()).equal("testResult", "0").count();
                simple.setUnqualifiedQuantity(new BigDecimal(unqualifiedCount+""));
            }
        }
    }
}
